package cn.chi.util;


import cn.chi.org.domain.Employee;
import cn.chi.org.mapper.EmployeeMapper;
import cn.chi.user.domain.LoginInfo;
import cn.chi.user.domain.User;
import cn.chi.user.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

public class LoginContext {

    public static Object getCurrent(HttpServletRequest request){
        //在没有被spring管理的类里面获取 spring管理的容器对象
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

        RedisTemplate redisTemplate = context.getBean("redisTemplate", RedisTemplate.class);
         /*
            获取当前的登录用户
                1.获取当前请求的token[请求头]
                2.通过token 获取 redis里面存储的loginInfo
                3.loginInfo的id 和type属性  获取当前的登录用户-》User
         */
        String token = request.getHeader("TOKEN");
        //2.通过token 获取 redis里面存储的loginInfo
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        //3.loginInfo的id 和type属性  获取当前的登录用户-》User
        if (loginInfo.getType()==1){//前台用户 User
            UserMapper userMapper = context.getBean(UserMapper.class);
            User user=userMapper.loadByLoginInfoId(loginInfo.getId());
            return  user;
        }else {//后台管理员用户  Employee
            EmployeeMapper employeeMapper = context.getBean(EmployeeMapper.class);
            //根据 查找对应的 Employee
            Employee employee = employeeMapper.loadByLoginInfoId(loginInfo.getId());
            return employee;
        }
    }
}
